package com.peng.leetcode.tree;

/**
 * MaxPathSum1
 * 124. 二叉树中的最大路径和
 * https://leetcode.cn/problems/binary-tree-maximum-path-sum/
 * <p>
 * Created on 2022/11/27
 *
 * @author lupeng
 */
public class MaxPathSum1 {

    public int maxPathSum(TreeNode root) {
        dfs(root);
        return ans;
    }

    private int ans = Integer.MIN_VALUE;

    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int l = Math.max(0, dfs(root.left));
        int r = Math.max(0, dfs(root.right));
        int val = root.val + l + r;
        ans = Math.max(val, ans);
        return root.val + Math.max(l, r);
    }

}
